package com.bianmaba.services.datacollection;

import com.bianmaba.beans.datacollection.TaskRunLog;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

@Component
@Scope("singleton")
public class TaskRunLogWriter implements Runnable {
    private static final Log LOG = LogFactory.getLog(TaskRunLogWriter.class);
    @Autowired
    private ITaskRunLogService logService;
    private final LinkedBlockingDeque<TaskRunLog> DEQUE = new LinkedBlockingDeque();


    @Override
    public void run() {
        LOG.info("日志写入器开始运行");
        while (true) {
            try {
                TaskRunLog log = this.DEQUE.takeFirst();
                logService.save(log);
            } catch (InterruptedException e) {
                LOG.debug("任务日志写入器终止运行。");
                break;
            } catch (Exception e) {
                LOG.error("运行日志保存出现异常。", e);
            }
        }
    }

    public void putLog(TaskRunLog taskRunLog) throws InterruptedException {
        DEQUE.putLast(taskRunLog);
    }

    public void putLog(List<TaskRunLog> logs) throws InterruptedException {
        if (logs != null && !logs.isEmpty()) {
            for (TaskRunLog log : logs) {
                DEQUE.putLast(log);
            }
        }
    }
}
